﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace TransportAbstractionLibrary.Common
{
    public sealed class SocketEventArgs : SocketAsyncEventArgs
    {

        internal SocketEventArgs(byte[] buffer, int bufferStart, int bufferSize)
        {
            base.SetBuffer(buffer, bufferStart, bufferSize);
            base.SetBuffer(bufferStart, bufferSize);
            this.bufferStart = bufferStart;
            this.bufferSize = bufferSize;
        }

        public void Initialize(IAsyncHost owner, EventArgsMode mode)
        {
            this.owner = owner;
            this.mode = mode;
        }


        int bufferStart;
        int bufferSize;

        IAsyncHost owner;
        EventArgsMode mode;

        public byte[] GetRecivedData()
        {
            byte[] buffer = new byte[this.BytesTransferred];
            System.Buffer.BlockCopy(this.Buffer, bufferStart, buffer, 0, this.BytesTransferred);
            return buffer;
        }

        public void SetData(byte[] buffer)
        {
            if (buffer.Length > bufferSize)
            {
                throw new TALSocketException(owner.GetProtocolBase(this), "Trying to send more data than fits in buffer!");
            }
            System.Buffer.BlockCopy(buffer, 0, this.Buffer, bufferStart, buffer.Length);
            SetBuffer(bufferStart, buffer.Length);
        }

        //tänk efter här hur ska du designa denna du har möjligheten att hoppa över event'et

        protected override void OnCompleted(SocketAsyncEventArgs e)
        {
            if (mode == EventArgsMode.Read && (e.LastOperation == SocketAsyncOperation.Receive || e.LastOperation == SocketAsyncOperation.ReceiveFrom))
            {
                owner.OnRecived(this);
            }
            else if (mode == EventArgsMode.Send && e.LastOperation == SocketAsyncOperation.Send || e.LastOperation == SocketAsyncOperation.SendTo)
            {
                owner.OnSent(this);
            }
            else
            {
                throw new TALSocketException(owner.GetProtocolBase(this), "Unhandeld LastOperation detected, value: " + e.LastOperation.ToString());
            }
        }
    }
}
